package muni.fi.bookscan;

import java.util.ArrayList;
import java.util.List;

import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;

/** First activity to be launched upon program start. */
public class MainActivity extends Activity {
	
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
    }
    
    
    
    /** 
     * Launching BarCode scanner.
     * 
     * @param view view object that triggered this event */
    public void onScanClick(View view){
    	IntentIntegrator integrator = new IntentIntegrator(this);
    	integrator.initiateScan();
    }
    
    /** BarCode result handle. */
    public void onActivityResult(int requestCode, int resultCode, Intent intent){
    	IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    	if(scanResult != null){
    		TextView text = (TextView) findViewById(R.id.input);
    		text.setText(scanResult.getContents());
    	} else {
    		
    	}
    }
    
    /** 
     * Launching SearchTask to search for a book in Google Books. 
     * 
     * @param view view object that triggered this event */
    public void onSearchClick(View view){
    	
    	//Getting the code from TextField(EditTExt)
    	TextView text = (TextView) findViewById(R.id.input);
    	String code = text.getText().toString();
    	if(!code.equals("")){
    		
    		//Checking is device has Internet access
    		if(deviceIsOnline()){
	    		//Starting a new Task to search for a book
	    		new SearchTask(MainActivity.this).execute(code);
	    		
    		}else{ //Showing the AlertDialog if there's no internet access
    			AlertDialog.Builder inetDialog = new AlertDialog.Builder(this);
    			inetDialog.setMessage("You need Internet access to search for a book")
    			.setPositiveButton("OK",new DialogInterface.OnClickListener() {					
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
    			
    			//AlertDialog alert = inetDialog.create();
    			inetDialog.show();
    		}
    		
    	}else{ //Showing the AlertDialog if there is nothing in the EditText field
    		AlertDialog.Builder searchDialog = new AlertDialog.Builder(this);
    		searchDialog.setMessage("No BarCode (or ISBN) added")
    		.setPositiveButton("OK", new DialogInterface.OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();					
				}
			});
    		
    		//AlertDialog alert = searchDialog.create();
    		searchDialog.show();
    	}
    }
    
    /** Checks whether device has internet access.
     * @return true if device has internet access */
    public boolean deviceIsOnline() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

        return cm.getActiveNetworkInfo() != null && 
           cm.getActiveNetworkInfo().isConnectedOrConnecting();
    }
    
    /** Creates a scrollable list of search results. 
     * 
     * @param allItemsInfo info about all found items */
    public void setUpBookList(final List<List<String>> allItemsInfo) {
    	ListView lv = (ListView)findViewById(R.id.bookList);
        
    	List<String> myList = new ArrayList<String>();
  	  	int itemsCount = allItemsInfo.size();
  	  	
    	for (int i = 0; i < itemsCount; i++) {
    		myList.add(allItemsInfo.get(i).get(0));
    	}
  	  	
    	if (itemsCount == 0) myList.add("0 books found");
  	  	ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList); 
        lv.setAdapter(adapter);
        
        if (itemsCount != 0) {
        	lv.setOnItemClickListener(new OnItemClickListener() {
        	    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    	          // Action performed on item click
    	          Log.i("bam", "pos: "+position+", id: "+id);
    	          
    	          Intent bookIntent = new Intent(MainActivity.this, BookInfoActivity.class);
    	          bookIntent.putStringArrayListExtra("bookInfo", (ArrayList<String>) allItemsInfo.get((int) id));
    	          MainActivity.this.startActivity(bookIntent);
    	        }
        	});
        }
    }
    

}